package com.qhy.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qhy.springcloud.api.Dept;
import com.qhy.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author qiuhongyu
 * @date 2020/9/25 17:26
 */
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;


    @GetMapping("/queryDept/{id}")
    @HystrixCommand(fallbackMethod = "hystrixQueryDept", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数超过了峰值，熔断器将会关闭
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率达到多少后跳闸

    })
    public Dept queryDept(@PathVariable("id") Long id) {
        Dept dept = deptService.queryDept(id);
        if (dept==null) {
            throw new RuntimeException("id=>" + id + "不存在该用户，或者信息无法找到");
        }
        return dept;
    }

    //备选方案
    public Dept hystrixQueryDept(@PathVariable("id") Long id) {
        Dept dept = new Dept();
        dept.setDname("id=>" + id + "没有对应的信息，null--Hystrix");

        return dept;
    }

    @PostMapping("/addDept")
    public void addDept(@RequestBody Dept dept) {
        deptService.addDept(dept);
    }

    @GetMapping("/queryDepts")
    public List<Dept> queryDepts() {
        List<Dept> deptList = deptService.queryDepts();
        return deptList;
    }
}
